<?php

namespace backend\controllers;
//引入导出excel辅助文件
// require_once(__DIR__ .'/../excel/PHPExcel.php');
// require_once(__DIR__ .'/../excel/PHPExcel/Writer/Excel2007.php');
// require_once(__DIR__ .'/../excel/PHPExcel/IOFactory.php');
use PHPExcel;
use Yii;
use common\models\Student;
use common\models\Post;
use common\models\StudentSearch;
use common\models\Yrclass;
use common\models\Card;
use common\models\Line;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
 
/**
 * StudentController implements the CRUD actions for Student model.
 */
class StudentController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Student models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new StudentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Student model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Student model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Student();
        $yrmodel = new Yrclass();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
// dd(Yii::$app->request->post());
// die;
            //给line表插入数据
            $arr = Yii::$app->request->post();
            $s_id = $model->attributes['id'];
            $class = "";
            foreach ($arr['YrClass']['name'] as  $value) {
                 $line = new Line();  //循环需实例化一个新对象
                 $line->class_id = $value;
                 $line->student_id = $s_id;
                 $line->save();
                
                 //查询班级
                 $res = Yrclass::find()->where(['id'=>$value])->asArray()->one();
                 $class .= $res['name'].",";
            }
           
           
             //添加学生表中的班级数据
             $model->id = $s_id;
             $model->class = $class;
             $model->update(array($s_id,$class));
            // die;
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'yrmodel' => $yrmodel 
            ]);
        }
    }

    /**
     * Updates an existing Student model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $yrmodel = new Yrclass();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            $arr = Yii::$app->request->post();
            $s_id = $model->attributes['id'];
            $class = "";
            foreach ($arr['YrClass']['name'] as  $value) {
                 $line = new Line();  //循环需实例化一个新对象
                 $line->class_id = $value;
                 $line->student_id = $s_id;
                 $line->update();

                 //查询班级
                 $res = Yrclass::find()->where(['id'=>$value])->asArray()->one();
                 $class .= $res['name'].",";
            }
           
           
             //更新学生表中的班级数据
             $model->id = $s_id;
             $model->class = $class;
             $model->update(array($s_id,$class));
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'yrmodel'=> $yrmodel,
            ]);
        }
    }

    /**
     * Deletes an existing Student model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Student model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Student the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Student::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
   
     public function actionExcel()
    {
        //查询学生表数据
        $result = Student::find()->select(['id','name','sex','age','parent_name','parent_tel','school','card_type','class','subscribe_class','subscribe_mark','subscribe_time','is_binding','mark','created_at','updated_at'])->asArray()->all();
        //查询卡类型作为提示信息
        $card = Card::find()->select('id,name')->asArray()->all();
        $ts = "";
        foreach($card as $c) {
            $ts .= implode(':',$c)."  ";
        }

        // dd($ts);
        // die;
        $dataResult = $result;      //todo:导出数据（自行设置） 
        $headTitle = "<h1>学生信息</h1><p style='color:red;'>&nbsp;卡类型：".$ts."</p><p style='color:red;'>&nbsp;是否绑定服务号：&nbsp;1:已绑定&nbsp;0：未绑定</p>";
        $time = time(); 
        $title = date('Y-m-d',$time)."学生信息表"; 
        $headtitle= "<tr style='height:50px;border-style:none;><th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >{$headTitle}</th></tr>"; 
        $titlename = "<tr> 
                    <th style='width:70px;' >编号</th> 
                    <th style='width:70px;' >姓名</th> 
                    <th style='width:40px;'>性别</th> 
                    <th style='width:70px;'>年龄</th> 
                    <th style='width:90px;'>父亲姓名</th> 
                    <th style='width:120px;'>父亲号码</th> 
                    <th style='width:200px;'>学校</th> 
                    <th style='width:70px;'>卡类型</th> 
                    <th style='width:70px;'>班级</th> 
                    <th style='width:90px;'>预约课程</th> 
                    <th style='width:200px;'>预约备注</th> 
                    <th style='width:140px;'>预约时间</th> 
                    <th style='width:90px;'>是否绑定服务号</th> 
                    <th style='width:200px;'>备注</th> 
                    <th style='width:140px;'>创建时间</th> 
                    <th style='width:140px;'>更新时间</th> 
                </tr>"; 
           $filename = $title.".xls"; 
           excelData($dataResult,$titlename,$headtitle,$filename); 
           
    }

    

}
